import axios from 'axios';
import qs from 'qs';
import {
    Message,
    Loading
} from 'element-ui';
import {
    baseURL
} from '@/utils/config';
import router from '@/router';
import store from '@/store/index';
import { getToken } from '@/utils/auth';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
NProgress.configure({showSpinner: false}); // NProgress Configuration

axios.defaults.withCredentials = true;
const ajax = axios.create({
    baseURL,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
        //"Content-Type": "application/json"
    },
    withCredentials: false,
    transformRequest: [function (data) {
        return qs.stringify(data);
    }]
})
let loadingInstance;
ajax.interceptors.request.use(
    config => {
        if (config.method === 'get') {
            let data = config.params;
            if (!data.loadingInstance) {
                // loadingInstance = Loading.service({
                //     lock: true,
                //     text: '拼命加载数据中...',
                //     spinner: 'el-icon-loading',
                //     background: 'rgba(0, 0, 0, 0.7)'
                // });
                NProgress.start(); // start progress bar
            }
            Object.keys(data).map(val => {
                if (data[val] === '' || data[val] === null) {
                    return delete data[val]
                }
            })
            const access_token = getToken() || '';
            let assignData
            if (config.url === '/v2/admin/login') {
                assignData = Object.assign({}, data)
            } else {
                assignData = Object.assign(data, {
                    token: access_token
                });
            }
            qs.stringify(assignData);
            config.params = assignData;
        } else {
            let data = config.data;
            if (!data.loadingInstance) {
                // loadingInstance = Loading.service({
                //     lock: true,
                //     text: '拼命加载数据中...',
                //     spinner: 'el-icon-loading',
                //     background: 'rgba(0, 0, 0, 0.7)'
                // });
                NProgress.start(); // start progress bar
            }
            Object.keys(data).map(val => {
                if (data[val] === '' || data[val] === null) {
                    return delete data[val]
                }
            })
            const access_token = getToken() || '';
            let assignData
            if (config.url === '/v2/admin/login') {
                assignData = Object.assign({}, data)
            } else {
                assignData = Object.assign(data, {
                    token: access_token
                });
            }
            config.data = assignData;
        }
        return config

    }, error => {
        if (loadingInstance) {
            loadingInstance.close();
        }
        NProgress.done(); // if current page is dashboard will not trigger	afterEach hook, so manually handle it
        return Promise.reject(error)
    })

ajax.interceptors.response.use(
    response => {
        const {
            code
        } = response.data;
        if (code !== 20000 && code !== 800000 && code !== 500203) { // 800000是轮询成功的情况。需要加一层判断, 是登录失效还是接口错误
            if (code === 300201 || code === 300202 || code === 300203 || code === 300301 || code === 300401|| code === 400201|| code === 400202|| code === 400203|| code === 400204) {
                Message.closeAll()
                Message.error('登录超时,请重新登录');
                store.dispatch('LoginOut').then(function () {
                    router.push({path: '/login'});
                })
            }
            Message.closeAll();
            if (response.data.message) {
                Message.error(response.data.message);
            }
        }
        if (loadingInstance) {
            loadingInstance.close();
        }
        NProgress.done(); // if current page is dashboard will not trigger	afterEach hook, so manually handle it
        return response.data

    }, err => {
      console.log(err)
        if (loadingInstance) {
            loadingInstance.close();
        }
        NProgress.done(); // if current page is dashboard will not trigger	afterEach hook, so manually handle it
        const {
            response,
            request
        } = err;
        const {
            status
        } = request;
        if (!response) {
            Message.closeAll();
            Message({
                message: `${status}:网络连接失败`,
                type: 'error',
                duration: 25 * 1000
            })
        } else {
            Message.closeAll();
            Message.error(`${status}:网络连接失败`);
        }

        return Promise.reject(err)
    })

export default ajax;